﻿using UnityEngine;
using UnityEngine.UIElements;

namespace winS.UnityEditor.UIElement
{
    public class ObjectField<T> : EditorField<T> where T : Object
    {
        private readonly global::UnityEditor.UIElements.ObjectField objectField;

        internal ObjectField(ElementFactory elementFactory) : base(elementFactory)
        {
            Add(objectField = new global::UnityEditor.UIElements.ObjectField());
            objectField.objectType = typeof(T);
            objectField.ElementAt(0).ElementAt(0).ElementAt(1).style.alignSelf = Align.Center;
            EditorElementUtility.ApplySubFieldStyle(objectField);
            objectField.RegisterValueChangedCallback(OnValueChangeCallback);
        }

        public override void SetValueWithoutNotify(T value)
        {
            base.SetValueWithoutNotify(value);
            objectField.SetValueWithoutNotify(value);
        }

        protected override void SetValue(T value)
        {
            base.SetValue(value);
            objectField.SetValueWithoutNotify(value);
        }

        private void OnValueChangeCallback(ChangeEvent<Object> changeEvent)
        {
            base.SetValue((T)changeEvent.newValue);
        }
    }
}